//
//  CrossViewController.m
//  Zhiche-Carriage
//
//  Created by LeeBruce on 16/7/26.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "CrossViewController.h"
#import "QiniuSDK.h"
#import "Common.h"
#import "WKProgressHUD.h"
//#import  <UIImageView+WebCache.h>
#import <UIButton+WebCache.h>
#import "ScrollImageViewController.h"

//#import "RLNetworkHelper.h"//网络判断
//#import "WKProgressHUD.h"//提示框
//#import <MJRefresh.h>//下拉刷新
//#import "NullView.h"

@interface CrossViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic,strong) UIButton *button1;
@property (nonatomic,strong) UIButton *button2;
@property (nonatomic,strong) UIButton *button3;
@property (nonatomic,strong) UIButton *button4;

@property (nonatomic,strong) NSMutableArray *postArr;


@property (nonatomic) NSInteger integer;
@property (nonatomic,copy) NSString *token;

@property (nonatomic,strong) WKProgressHUD *hud;


@end

@implementation CrossViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.postArr = [NSMutableArray array];
    _integer = 0;
    [self initDataSource];
    
//    [self initSubView];

}


-(void)initDataSource
{
    NSString *string = [NSString stringWithFormat:@"%@/%@?id=%@",mission_detail,self.orderId,self.orderId];
    
    [Common requestWithUrlString:string contentType:application_json finished:^(id responseObj) {
        
        
        if ([responseObj[@"success"] boolValue]) {

        self.dataDictionary = [NSMutableDictionary dictionaryWithDictionary:responseObj[@"data"]];
        
        if ([[self.dataDictionary allKeys]count] > 0) {
            
            if (self.hiddenPriceTeger != 10) {
                //公司派单
                self.tableView.frame = CGRectMake(0, cellHeight, screenWidth, cellHeight * (10 + [self.dataDictionary[@"vehicles"] count]) - cellHeight * 2 - 10);
                //个人派单
            } else {
                self.tableView.frame = CGRectMake(0, cellHeight, screenWidth, cellHeight * (10 + [self.dataDictionary[@"vehicles"] count]) );
                
            }

            
//            self.tableView.frame = CGRectMake(0, cellHeight, screenWidth, cellHeight * (10 + [self.dataDictionary[@"vehicles"] count]) );
            
            [self initSubView];
            self.orderNumberL.text = self.dataDictionary[@"waybillCode"];

            [self.tableView reloadData];
            
            [self getValueString];
        }
            
        } else {
            
            //获取失败信息
            [WKProgressHUD popMessage:responseObj[@"message"] inView:self.view duration:1.5 animated:YES];
            
        }
        
        
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
        
    }];
    
    
}

-(void)getValueString
{

    
    for (int i = 0; i < [self.dataDictionary[@"sendPics"] count]; i ++) {
       
        if ([self.dataDictionary[@"sendPics"][i][@"type"] integerValue] == 2010) {
           
            NSString *string1 = [NSString stringWithFormat:@"%@",self.dataDictionary[@"sendPics"][i][@"picKey"]];
            NSURL *url = [NSURL URLWithString:string1];
            [self.button1 sd_setImageWithURL:url forState:UIControlStateNormal];
//            [self.button1 sd_setImageWithURL:url forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"bad_picture"]];
//        [self.button1 sd_setImageWithURL:url forState:UIControlStateNormal completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
           
            
            
//        }];

        } else {
            
            NSString *string1 = [NSString stringWithFormat:@"%@",self.dataDictionary[@"sendPics"][i][@"picKey"]];
            NSURL *url = [NSURL URLWithString:string1];
            [self.button2 sd_setImageWithURL:url forState:UIControlStateNormal];
        }
    }
 

}


-(void)initSubView
{
    
    UIView *firstV = [self backViewWithFrame:CGRectMake(0, CGRectGetMaxY(self.tableView.frame) - 10 , screenWidth, cellHeight + 100 * kHeight) andString:@"发车照片"];
    
    //交接单照片
    self.button1 = [UIButton buttonWithType:UIButtonTypeCustom];
//    self.button1.userInteractionEnabled = NO;
    UIView *jiaojieV = [self backViewWithButton:self.button1 andString:@"交接单照片" andFloat:18];
    
    [firstV addSubview:jiaojieV];
    
    //车辆照片
    self.button2 = [UIButton buttonWithType:UIButtonTypeCustom];
//    self.button2.userInteractionEnabled = NO;
    
    UIView *carV = [self backViewWithButton:self.button2 andString:@"车辆照片" andFloat:38 + 70 * kHeight ];
    
    [firstV addSubview:carV];
    
    
    
    UIView *secondV = [self backViewWithFrame:CGRectMake(0, CGRectGetMaxY(firstV.frame) + 10 , screenWidth, cellHeight + 100 * kHeight) andString:@"卸车照片"];
    
    //交接单照片
    self.button3 = [UIButton buttonWithType:UIButtonTypeCustom];
    UIView *jiaojie1V = [self backViewWithButton:self.button3 andString:@"交接单照片" andFloat:18];
    
    [secondV addSubview:jiaojie1V];
    
    //车辆照片
    self.button4 = [UIButton buttonWithType:UIButtonTypeCustom];
    
    UIView *car1V = [self backViewWithButton:self.button4 andString:@"车辆照片" andFloat:38 + 70 * kWidth];
    
    [secondV addSubview:car1V];
    
    
    
    UIButton *confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
    confirmButton.frame = CGRectMake(18, CGRectGetMaxY(secondV.frame) + 20, screenWidth - 36, Button_height);
    [confirmButton setTitle:@"确认交车" forState:UIControlStateNormal];
    [confirmButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    [confirmButton setBackgroundColor:YellowColor];
    [confirmButton addTarget:self action:@selector(confirmButton) forControlEvents:UIControlEventTouchUpInside];
    confirmButton.layer.cornerRadius = 5;
    
    [self.scrollView addSubview:confirmButton];
    
    self.scrollView.contentSize = CGSizeMake(screenWidth, CGRectGetMaxY(confirmButton.frame) + 20);
    
    
}

#pragma mark 确认交车
-(void)confirmButton
{
    if (self.postArr.count != 2) {
        
        [WKProgressHUD popMessage:@"请将信息补充完整" inView:self.view duration:1.5 animated:YES];
        
        
    } else {
        
        NSData * jsonData = [NSJSONSerialization dataWithJSONObject:self.postArr options:NSJSONWritingPrettyPrinted error:nil];
        NSString * jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
        Common *c = [[Common alloc]init];
        
        
        NSDictionary *dictionary = @{@"id":self.orderId,@"attachs":jsonString};
        
        
        [c afPostRequestWithUrlString:waybill_delivery parms:dictionary finishedBlock:^(id responseObj) {

            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
            
            if ([dic[@"success"] boolValue]) {
               
                [WKProgressHUD popMessage:dic[@"message"] inView:self.view duration:1.5 animated:YES];
                
                //延迟执行
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [self backAction];
                    
                });

            } else {
                
                [WKProgressHUD popMessage:dic[@"message"] inView:self.view duration:1.5 animated:YES];

            }
            
            
        } failedBlock:^(NSString *errorMsg) {
            
            [self.hud dismiss:YES];
            
            NSLog(@"%@",errorMsg);
        }];
        
        
        
    }

}



-(UIView *)backViewWithFrame:(CGRect)frame andString:(NSString *)string
{
    UIView *view = [[UIView alloc]initWithFrame:frame];
    view.backgroundColor = WhiteColor;
    [self.scrollView addSubview:view];
    
    UILabel *titleL = [[UILabel alloc]initWithFrame:CGRectMake(18, 0, 100, cellHeight)];
    titleL.text = string;
    titleL.textColor = littleBlackColor;
    titleL.font = Font(14);
    [view addSubview:titleL];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, cellHeight, screenWidth, 0.5)];
    label.backgroundColor = LineGrayColor;
    [view addSubview:label];
    
    return view;

}


-(UIView *)backViewWithButton:(UIButton *)button andString:(NSString *)string andFloat:(CGFloat)x
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(x, cellHeight + 10 * kHeight, 70 * kWidth, 90 * kHeight)];
    
    button.frame = CGRectMake(0, 0, 70 * kHeight, 70 * kHeight);
    [button setBackgroundImage:[UIImage imageNamed:@"car_add"] forState:UIControlStateNormal];
    [view addSubview:button];
    [button addTarget:self action:@selector(getPicture:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMidX(button.frame) - 45, CGRectGetMaxY(button.frame), 90, 20 * kHeight)];
    label.text = string;
    label.font = Font(10);
    label.textColor = carScrollColor;
    label.textAlignment = NSTextAlignmentCenter;
    
    [view addSubview:label];
    return view;
}


-(void)getPicture:(UIButton *)sender
{
    //浏览大图
    if (sender == self.button1 || sender == self.button2) {
        
            if ([self.dataDictionary[@"sendPics"] count] > 0) {
                
                NSMutableArray *arr = [NSMutableArray array];
                for (int i = 0; i < [self.dataDictionary[@"sendPics"] count]; i ++) {
                    
                    NSString *string1 = [NSString stringWithFormat:@"%@",self.dataDictionary[@"sendPics"][i][@"picKey"]];
                    NSURL *url = [NSURL URLWithString:string1];
                    [arr addObject:url];
                    
                }
                
                ScrollImageViewController *scrollV = [[ScrollImageViewController alloc]init];
                
                scrollV.imageArr =  arr;
                
                [self.navigationController pushViewController:scrollV animated:YES];

                
            }
        
    }
    
    //获取图片
    
    if (sender == self.button3) {
        _integer = 1;
        
        [self tapSelectPicture];

        
        
    } else if(sender == self.button4) {
        _integer = 2;
        
        [self tapSelectPicture];

    }
    
//    [self tapSelectPicture];
    
}

//获取图片
-(void)tapSelectPicture
{
    __weak typeof(self) weakSelf = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [weakSelf getPictureFromCamera];
        
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"从相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf getPictureFromLibrary];
        
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    
    
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark 拍照
-(void)getPictureFromCamera
{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark 从相册选取
-(void)getPictureFromLibrary
{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [self presentViewController:picker animated:YES completion:nil];
    
}


#pragma mark UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        
        if (_integer == 1) {
            [self.button3 setImage:image forState:UIControlStateNormal];
        } else {
            [self.button4 setImage:image forState:UIControlStateNormal];
        }
        
        self.hud  = [WKProgressHUD showInView:self.view withText:@"" animated:YES];

        
        //上传服务器
        [self getTokenFromQN];
        
    }];
}


-(NSData *)getImageWith:(UIImage *)image
{
    NSData *data = nil;
    if (UIImagePNGRepresentation(image)) {
        
        data = UIImageJPEGRepresentation(image, 1);
        
        
    } else {
        data = UIImagePNGRepresentation(image);
        
        
    }
    
    return data;
}

#pragma mark 从七牛获取Token
-(void)getTokenFromQN
{
    
    [Common requestWithUrlString:qiniu_token contentType:application_json finished:^(id responseObj) {
        if ([responseObj[@"success"] boolValue]) {
            
            
            self.token = responseObj[@"data"];

            if (_integer == 1) {
                [self uploadImageToQNWithData:[self getImageWith:self.button3.imageView.image]];
                
            } else {
                [self uploadImageToQNWithData:[self getImageWith:self.button4.imageView.image]];
                
            }
            
        }
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
    
    
    
}

-(void)uploadImageToQNWithData:(NSData *)data
{
    
    QNUploadManager *upManager = [[QNUploadManager alloc]init];
    
    QNUploadOption *uploadOption = [[QNUploadOption alloc]initWithMime:nil progressHandler:^(NSString *key, float percent) {
        
    } params:nil checkCrc:NO cancellationSignal:nil];
    
    [upManager putData:data key:nil token:self.token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        
        
        NSDictionary *dic ;
        
        if (_integer == 1) {
            dic = @{@"image":resp[@"key"],
                    @"type":@"3010"};
        } else {
            dic = @{@"type":@"3020",
                    @"image":resp[@"key"]};
        }
        
        if (self.postArr.count > 0) {
            
            for (int i = 0 ;i < self.postArr.count; i++) {
                
                if ([self.postArr[i][@"type"] isEqualToString:dic[@"type"]]) {
                    
                    [self.postArr removeObjectAtIndex:i];
                }
            }
            
            [self.postArr addObject:dic];
            
        } else {
            [self.postArr addObject:dic];
            
        }
        [self.hud dismiss:YES];

        
    } option:uploadOption];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
